var e = getApp(), t = require("../../../utils/live-video-common.js");

Page(Object.assign({
    data: {
        userInfo: {},
        userList: [],
        messageList: [],
        pusher: {
            user_id: "",
            nick_name: "",
            avatar_url: ""
        },
        options: {
            room_id: "",
            building_name: "",
            anchor_id: ""
        },
        screenHeight: 1e3,
        rtcConfig: {
            sdkAppID: "",
            userID: "",
            userSig: "",
            template: "custom",
            enableMic: !1
        },
        myConfig: {
            enableMic: !1,
            role: 3
        },
        house: {
            housename: "望京E座302",
            houseid: "12322",
            thumbimg: "https://fang-oss.haozu.com/cms/index/2019/12/13/hemmMBzGfQ.jpg?x-oss-process=image/resize,m_fill,w_492,h_356/quality,Q_90/crop,g_center,x_0,y_0,h_356,w_492"
        },
        isEnter: !1,
        showUserList: !1
    },
    visiter: function() {
        this.setData({
            showUserList: !0
        });
    },
    mergeArrayUserHandle: function(e) {
        var t = this.data.userList;
        return e.forEach(function(e, o) {
            var n = t.filter(function(t, o) {
                return t.user_id === e.user_id;
            });
            n.length > 0 ? (n[0].nick_name = e.nick_name, n[0].avatar_url = e.avatar_url) : t.push(e);
        }), t;
    },
    getRemoteUserListInfo: function() {
        var e = this, t = this.trtcComponent.getRemoteUserList();
        console.log(t);
        var o = t.map(function(e, t) {
            return e.userID;
        });
        e.getUsersInfo(o).then(function(t) {
            e.setData({
                userList: e.mergeArrayUserHandle(t)
            }), "" === e.data.pusher.avatar_url && e.setData({
                pusher: e.getRemoteUserInfo(e.data.pusher.user_id)
            });
        });
    },
    getUsersInfo: function(t) {
        return new Promise(function(o, n) {
            t.length > 0 ? wx.request({
                method: "get",
                url: e.globalData.uchaozuBase + "/api/miniapps/login/userinfo",
                data: Object.assign({
                    ids: t.join(",")
                }, e.getSecret()),
                success: function(e) {
                    if ("200" == e.data.code) {
                        var t = e.data.data;
                        o(t.map(function(e, t) {
                            return e.role = 3, e;
                        }));
                    } else o([]);
                },
                fail: function(e) {
                    console.log(e), o([]);
                }
            }) : o([]);
        });
    },
    getSdkObj: function(t) {
        var o = e.getMobSecret("/api/wechat/get-trtc-sign", {
            uid: t.user_id
        });
        return console.log(o), new Promise(function(t, n) {
            wx.request({
                url: e.globalData.liveBase + "/api/wechat/get-trtc-sign",
                data: o,
                header: {
                    "content-type": "application/json"
                },
                success: function(o) {
                    if ("0" == o.data.errorno) {
                        var n = {
                            sdkAppID: o.data.data.sdkAppId,
                            userSig: o.data.data.userSign
                        };
                        e.globalData.videoObj = n, t();
                    }
                },
                fail: function(e) {
                    n(e);
                }
            });
        });
    },
    checkVersion: function() {
        var t = e.globalData.SDKVersion + "";
        if (console.log("微信基础库版本号：" + t), !(e.compareVersion(t, "2.10.0") >= 0)) return wx.showModal({
            title: "提示",
            content: "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"
        }), !1;
        var o = e.globalData.system;
        if (o.indexOf("iOS") > -1) {
            var n = o.split(" ")[1];
            if (e.compareVersion(n, "7.0.9") < 0) return wx.showModal({
                title: "提示",
                content: "当前系统版本过低，无法使用该功能，请升级到7.0.9及以上版本后重试。"
            }), !1;
        } else if (o.indexOf("Android") > -1) {
            var i = o.split(" ")[1];
            if (e.compareVersion(i, "7.0.8") < 0) return wx.showModal({
                title: "提示",
                content: "当前系统版本过低，无法使用该功能，请升级到7.0.8及以上版本后重试。"
            }), !1;
        }
        return !0;
    },
    onLoad: function(t) {
        this.setData({
            options: t,
            screenHeight: e.globalData.screenHeight,
            headerHeight: e.globalData.headerHeight,
            statusBarHeight: e.globalData.statusBarHeight
        });
    },
    enterRoomHandle: function(e) {
        var t = this, o = e.sdkAppID, n = e.userSig;
        this.setData({
            rtcConfig: {
                sdkAppID: o,
                userID: this.data.rtcConfig.userID + "",
                userSig: n,
                enableMic: this.data.rtcConfig.enableMic,
                template: "custom",
                roomID: Number(this.data.options.room_id),
                cloudenv: "PRO",
                scene: "rtc",
                localVideo: !1,
                localAudio: !1,
                enableEarMonitor: !1,
                enableAutoFocus: !0,
                localMirror: "auto",
                enableAgc: !0,
                enableAns: !0,
                encsmall: !1,
                frontCamera: "front",
                resolution: "HD",
                debugMode: !1,
                beautyLevel: 9,
                audioVolumeType: "media",
                enableIM: !0,
                videoWidth: 540,
                videoHeight: 960,
                minBitrate: 600,
                maxBitrate: 1500,
                enableBackgroundMute: !0
            }
        }, function() {
            console.log(t.data.options.room_id), t.trtcComponent.enterRoom({
                roomID: Number(t.data.options.room_id)
            }).then(function() {
                console.log("房间进入成功！！"), t.getRemoteUserListInfo();
            }).catch(function(e) {
                console.error("room joinRoom 进房失败:", e);
            });
        });
    },
    bindTRTCRoomEvent: function() {
        var t = this, o = this.trtcComponent.EVENT, n = this.trtcComponent;
        this.timestamp = [], this.trtcComponent.on(o.LOCAL_JOIN, function(e) {
            console.log("* room LOCAL_JOIN", e), t.enterRoomSuccess();
        }), this.trtcComponent.on(o.LOCAL_LEAVE, function(e) {
            console.log("* room LOCAL_LEAVE", e);
        }), this.trtcComponent.on(o.ERROR, function(e) {
            console.log("* room ERROR", e);
        }), this.trtcComponent.on(o.REMOTE_USER_JOIN, function(e) {
            console.log("* 远端用户进房", e, t.trtcComponent.getRemoteUserList());
            var o = e.data.userID;
            t.addOnePerson(o);
        }), this.trtcComponent.on(o.REMOTE_USER_LEAVE, function(e) {
            console.log("* 远端用户退出", e, t.trtcComponent.getRemoteUserList());
            var o = t.data.messageList, n = t.data.userList, i = n.filter(function(t, o) {
                return t.user_id !== e.data.userID;
            }), a = n.filter(function(t, o) {
                return t.user_id === e.data.userID;
            });
            0 === a.length && (a[0] = {
                nick_name: e.data.userID
            }), o.push(Object.assign({
                messageText: a[0].nick_name + "离开了直播间"
            }, a[0])), t.setData({
                userList: i,
                messageList: o
            });
        }), this.trtcComponent.on(o.REMOTE_VIDEO_ADD, function(e) {
            console.log("###远端用户推送视频！###", e.data.userID);
            var o = e.data.userID, n = e.data.streamType;
            if (t.trtcComponent.subscribeRemoteVideo({
                userID: o,
                streamType: n
            }), t.data.pusher.user_id === o) return !1;
            "" !== t.data.pusher.user_id ? t.viewSwitch(t.data.pusher.user_id, o) : t.viewSwitch(null, o), 
            t.setData({
                pusher: t.getRemoteUserInfo(o)
            });
        }), this.trtcComponent.on(o.REMOTE_VIDEO_REMOVE, function(e) {
            console.log("* room REMOTE_VIDEO_REMOVE", e, t.trtcComponent.getRemoteUserList());
        }), this.trtcComponent.on(o.REMOTE_AUDIO_ADD, function(e) {
            console.log("* room REMOTE_AUDIO_ADD", e, t.trtcComponent.getRemoteUserList());
            var o = e.data.userID;
            n.subscribeRemoteAudio({
                userID: o
            });
        }), this.trtcComponent.on(o.REMOTE_AUDIO_REMOVE, function(e) {
            console.log("* room REMOTE_AUDIO_REMOVE", e, t.trtcComponent.getRemoteUserList());
        }), this.trtcComponent.on(o.IM_SDK_READY, function(e) {
            console.log("* room IM_SDK_READY", e), "sdkStateReady" === e.data.name && t.trtcComponent.sendGroupTextMessage({
                roomID: t.data.options.room_id,
                message: JSON.stringify({
                    user_id: t.data.userInfo.user_id,
                    code: "20000"
                })
            });
        }), this.trtcComponent.on(o.IM_MESSAGE_RECEIVED, function(o) {
            var n = t;
            console.log("* room IM_MESSAGE_RECEIVED", o);
            var i = o.data.data[0];
            if ("GROUP" === i.conversationType) {
                var a = JSON.parse(i.payload.text);
                if ("20000" === a.code && t.backPerson(a.user_id), "20001" === a.code && t.leavePerson(a.user_id), 
                "20010" === a.code) {
                    n.data.userInfo.user_id;
                    n.trtcComponent.data.pusher.enableCamera ? n.trtcComponent.unpublishLocalVideo().then(function() {
                        n.trtcComponent.unpublishLocalAudio(), t.trtcComponent.data.exitIMThrottle = !0, 
                        t.trtcComponent.exitRoom().then(function() {
                            console.log("20010房间退出成功"), n.setData({
                                rtcConfig: n.data.rtcConfig
                            }, function() {
                                n.trtcComponent.enterRoom({
                                    roomID: n.data.options.room_id
                                }).then(function(e) {
                                    console.log("20010房间进入成功"), n.trtcComponent.data.exitIMThrottle = !1, n.trtcComponent.setViewVisible({
                                        userID: n.data.userInfo.user_id,
                                        streamType: "main",
                                        isVisible: !1
                                    }), n.data.myConfig.enableMic && n.trtcComponent.publishLocalAudio(), n.viewSwitch(null, i.from), 
                                    n.setData({
                                        pusher: n.getRemoteUserInfo(i.from)
                                    }), wx.showToast({
                                        title: "创建人指定" + n.data.pusher.nick_name + "为主持人，您被取消主持人权限",
                                        duration: 3e3,
                                        icon: "none",
                                        success: function() {}
                                    });
                                });
                            });
                        });
                    }) : (n.viewSwitch(n.data.pusher.user_id, i.from), n.setData({
                        pusher: n.getRemoteUserInfo(i.from)
                    }));
                }
                return "40000" === a.code && wx.showToast({
                    title: "房间解散，直播结束",
                    icon: "none",
                    duration: 3e3,
                    success: function() {
                        setTimeout(function() {
                            wx.reLaunch({
                                url: "/pages/live-video/video-detail/index?roomID=" + n.data.options.room_id
                            });
                        }, 3e3);
                    }
                }), !1;
            }
            "code:10000" !== i.payload.data && "code:10010" !== i.payload.data || wx.showModal({
                title: i.payload.description,
                content: "",
                success: function(t) {
                    t.confirm ? (console.log("用户点击确定"), n.trtcComponent.sendGroupTextMessage({
                        roomID: n.data.options.room_id,
                        message: JSON.stringify({
                            user_id: n.data.userInfo.user_id,
                            code: "20010"
                        })
                    }), e.cameraPower().then(function(e) {
                        if (e) {
                            n.trtcComponent.publishLocalVideo();
                            var t = n.data.userInfo.user_id + "";
                            n.viewSwitch(n.data.pusher.user_id, t), n.setData({
                                pusher: n.getRemoteUserInfo(t)
                            });
                        }
                    })) : t.cancel && (console.log("用户点击取消"), n.trtcComponent.sendC2CCustomMessage({
                        userID: i.from,
                        payload: {
                            data: "code:10002",
                            description: "拒绝成为主持人",
                            extension: ""
                        }
                    }));
                }
            });
        });
    },
    addOnePerson: function(e) {
        var t = this;
        0 === this.data.userList.filter(function(t, o) {
            return t.user_id === e;
        }).length && this.getUsersInfo([ e ]).then(function(e) {
            if (e.length) {
                t.data.userList;
                var o = t.data.messageList;
                o.push(Object.assign({
                    messageText: e[0].nick_name + "进入了直播间"
                }, e[0])), t.setData({
                    userList: t.mergeArrayUserHandle(e),
                    messageList: o
                }), "" === t.data.pusher.avatar_url && t.setData({
                    pusher: t.getRemoteUserInfo(t.data.pusher.user_id)
                });
            }
        });
    },
    getRemoteUserInfo: function(e) {
        var t = this.data.userList.filter(function(t, o) {
            return t.user_id === e;
        });
        return t.length ? t[0] : {
            user_id: e,
            nick_name: e,
            avatar_url: ""
        };
    },
    viewSwitch: function(e, t) {
        var o = this;
        null === e ? (o.trtcComponent.setViewVisible({
            userID: t,
            isVisible: !0,
            streamType: "main"
        }), this.trtcComponent.setViewRect({
            userID: t,
            streamType: "main",
            xAxis: "0rpx",
            yAxis: "0rpx",
            width: "750rpx",
            height: this.data.screenHeight + "rpx"
        })) : (this.trtcComponent.setViewVisible({
            userID: e,
            isVisible: !1,
            streamType: "main"
        }), setTimeout(function() {
            o.trtcComponent.setViewVisible({
                userID: t,
                isVisible: !0,
                streamType: "main"
            }), o.trtcComponent.setViewRect({
                userID: t,
                streamType: "main",
                xAxis: "0rpx",
                yAxis: "0rpx",
                width: "750rpx",
                height: o.data.screenHeight + "rpx"
            });
        }, 2e3));
    },
    handlePublishAudio: function() {
        if (this.data.myConfig.enableMic) {
            this.trtcComponent.unpublishLocalAudio();
            var e = this.data.myConfig;
            e.enableMic = !1, this.setData({
                myConfig: e
            }, function() {
                wx.showToast({
                    title: "您已关闭麦克风",
                    icon: "none",
                    duration: 500
                });
            });
        } else {
            this.trtcComponent.publishLocalAudio();
            var t = this.data.myConfig;
            t.enableMic = !0, this.setData({
                myConfig: t
            }, function() {
                wx.showToast({
                    title: "您已开启麦克风",
                    icon: "none",
                    duration: 500
                });
            });
        }
    },
    switchCamera: function() {
        this.trtcComponent.switchCamera();
    },
    exitRoom: function() {
        var e = this;
        this.data.pusher.user_id !== this.data.userInfo.user_id ? this.trtcComponent && this.trtcComponent.exitRoom().then(function() {
            wx.reLaunch({
                url: "/pages/my/index"
            });
        }) : wx.showModal({
            title: "请选择退出类型",
            content: "",
            cancelText: "退出直播",
            confirmText: "退出房间",
            success: function(t) {
                t.confirm ? (e.trtcComponent.exitRoom().then(function() {
                    wx.reLaunch({
                        url: "/pages/my/index"
                    });
                }), e.trtcComponent.unpublishLocalVideo(), e.trtcComponent.unpublishLocalAudio()) : t.cancel && (e.trtcComponent.sendC2CCustomMessage({
                    userID: e.data.options.anchor_id,
                    payload: {
                        data: "code:10003",
                        description: "停止作为主持人",
                        extension: ""
                    }
                }), e.trtcComponent.unpublishLocalVideo(), e.trtcComponent.unpublishLocalAudio(), 
                setTimeout(function() {
                    e.data.myConfig.enableMic && e.trtcComponent.publishLocalAudio();
                }, 1e3), e.pusherClear(), e.trtcComponent.setViewVisible({
                    userID: e.data.userInfo.user_id,
                    isVisible: !1,
                    streamType: "main"
                }));
            }
        });
    },
    pusherClear: function() {
        this.setData({
            pusher: {
                user_id: "",
                nick_name: "",
                avatar_url: ""
            }
        });
    },
    closePerson: function() {
        this.setData({
            showUserList: !1
        });
    },
    onReady: function() {},
    getRoomInfo: function() {
        var t = e.getMobSecret("/api/wechat/get-room-info", {
            uid: e.globalData.userInfo.user_id,
            room_id: this.data.options.room_id
        });
        return console.log(t), new Promise(function(o, n) {
            wx.request({
                url: e.globalData.liveBase + "/api/wechat/get-room-info",
                data: t,
                header: {
                    "content-type": "application/json"
                },
                success: function(e) {
                    o(e);
                },
                fail: function(e) {
                    n(e);
                }
            });
        });
    },
    enterRoomSuccess: function() {
        var t = e.getMobSecret("/api/wechat/enter-room", {
            uid: e.globalData.userInfo.user_id,
            room_id: this.data.options.room_id,
            user_type: 2
        });
        wx.request({
            url: e.globalData.liveBase + "/api/wechat/enter-room",
            data: t,
            header: {
                "content-type": "application/json"
            },
            success: function(e) {
                "0" == e.data.errorno ? console.log("进入房间成功，告诉后台") : (console.log(e.data.errormsg), 
                wx.showLoading({
                    title: e.data.errormsg,
                    duration: 3e3
                }));
            },
            fail: function(e) {}
        });
    },
    checkFun: function() {
        var t = this;
        this.getRoomInfo().then(function(o) {
            console.log(o), t.setData({
                isEnter: !0
            }), "0" == o.data.errorno ? 3 == o.data.data.room_status || 4 == o.data.data.room_status ? wx.reLaunch({
                url: "/pages/live-video/video-detail/index?roomID=" + t.data.options.room_id
            }) : (t.trtcComponent = t.selectComponent("#trtc-component"), t.trtcComponent.setViewVisible({
                userID: t.data.userInfo.user_id,
                isVisible: !1,
                streamType: "main"
            }), t.bindTRTCRoomEvent(), t.enterRoomHandle(e.globalData.videoObj)) : (console.log(o.data.errormsg), 
            wx.showLoading({
                title: o.data.errormsg,
                duration: 3e3
            }));
        });
    },
    onShow: function() {
        var t = this, o = this;
        if (wx.setKeepScreenOn({
            keepScreenOn: !0
        }), this.data.isEnter) return console.log("onshow 执行"), this.trtcComponent.sendGroupTextMessage({
            roomID: this.data.options.room_id,
            message: JSON.stringify({
                user_id: this.data.userInfo.user_id,
                code: "20000"
            })
        }), !1;
        e.soundPower().then(function(n) {
            if (console.log(n), n) {
                var i = e.globalData.userInfo;
                if (i && i.user_id) {
                    if (i.user_id === o.data.options.anchor_id) return wx.reLaunch({
                        url: "/pages/live-video/live-video/index?roomID=" + o.data.options.room_id + "&building_name=" + o.data.options.building_name + "&is_room=true"
                    }), !1;
                    if (!t.checkVersion()) return !1;
                    i.user_id = i.user_id + "", t.setData({
                        userInfo: i,
                        userList: [ {
                            user_id: i.user_id,
                            nick_name: i.nick_name,
                            avatar_url: i.avatar_url,
                            role: 3
                        } ]
                    });
                    var a = o.data.rtcConfig;
                    a.userID = i.user_id, o.setData({
                        rtcConfig: a
                    }), console.log("登录的人是" + i.user_id), i.videoObj && i.videoObj.sdkAppId ? o.checkFun() : t.getSdkObj(i).then(function() {
                        o.checkFun();
                    });
                } else wx.navigateTo({
                    url: "/pages/getinfo/index"
                }), e.globalData.needBack = !0;
            }
        });
    },
    onHide: function() {
        if (console.log("####页面隐藏!"), !this.data.isEnter) return !1;
        this.trtcComponent.sendGroupTextMessage({
            roomID: this.data.options.room_id,
            message: JSON.stringify({
                user_id: this.data.userInfo.user_id,
                code: "20001"
            })
        }), wx.setKeepScreenOn({
            keepScreenOn: !1
        });
    },
    onUnload: function() {},
    onPullDownRefresh: function() {},
    onReachBottom: function() {},
    onShareAppMessage: function(t) {
        var o = this, n = "/images/video/project_temp.jpg";
        if (null != e.globalData.userInfo) {
            var i = e.getMobSecret("/api/wechat/get-share-image", {
                uid: e.globalData.userInfo.user_id,
                text: this.data.options.building_name
            }, "GET", 604800);
            console.log(i), n = e.globalData.liveBase + "/api/wechat/get-share-image?sign=" + i.sign + "&secret_id=" + i.secret_id + "&uid=" + e.globalData.userInfo.user_id + "&text=" + o.data.options.building_name + "&timestamp=" + i.timestamp + "&valid_time=604800";
        }
        return {
            title: o.data.options.building_name + "-看房直播",
            imageUrl: n,
            path: "/pages/live-video/live-video/room?room_id=" + o.data.options.room_id + "&building_name=" + o.data.options.building_name + "&anchor_id=" + o.data.options.anchor_id
        };
    }
}, t));